<template>
    <view class="bottom">
        <Header></Header>
        <view class="back">
            <u-icon style="border: 1px #00eaff solid;border-radius: 50%;margin-left: 50rpx;margin-right: 20rpx"
                    name="arrow-left" color="#00eaff" @click="back"></u-icon>
            <text style="color: #00eaff;padding-right: 30rpx">Blind box unboxing</text>
            <!--            <u-icon name="question-circle-fill" color="#00eaff" @click="toHelp"></u-icon>-->
        </view>
        <view>
            <u-popup ref="help" mode="center" closeable :width="windowsWidth+'px'">
                <view class="popup">
                    <view class="title">
                        <h3>玩法说明</h3>
                    </view>
                    <view class="content">
                        <view class="item">
                            <text>1、选择开箱次数后，支付对应的钻石即可开启</text>
                        </view>
                        <view class="item">
                            <text>2、下方的掉落概率可以看到每个饰品的具体概率
                            </text>
                        </view>
                        <view class="item">
                            <text>3、每次开启都属于独立事件，不受其他玩家和您之前开箱影响，多次开启不会增加概率</text>
                        </view>
                        <view class="item">
                            <text>
                                举例1：箱子内A和B两个饰品概率各为50%，连续开启时，无法保证结果稳定是ABABAB
                            </text>
                        </view>
                        <view class="item">
                            <text>
                                举例2：某饰品概率为10%，并不是每开启10次就必出1次。可能20次才出1次，也可能10次出多次
                            </text>
                        </view>
                    </view>
                </view>
            </u-popup>
        </view>
        <view>
            <h2 class="title">
                <u-image src="@/static/images/boxDetail-title-right.png" width="30rpx" height="30rpx"></u-image>
                <text style="padding: 20rpx">
                    {{ box.box_name }}
                </text>
                <u-image src="@/static/images/boxDetail-title-left.png" width="30rpx" height="30rpx"></u-image>
            </h2>
            <view class="box">
                <view class="box_banner">
                    <view class="box_banner_images">
                        <u-image :src="box.box_banner_images[0]" width="512rpx" height="384rpx"></u-image>
                    </view>
                </view>
            </view>

            <view class="radio-group">
                <view class="radio-item" v-for="(item, index) in buttonItems" :key="index">
                    <u-button class="button" :class="{'radio-button': index === selectedIndex}" throttle-time="0"
                              hover-class="none"
                              @click="selectItem(index)">
                        ✖{{ item }}
                    </u-button>
                </view>
            </view>

            <view class="skip">
                <u-switch v-model="skip" size="34" active-color="#98E184"
                          inactive-color="transparent"></u-switch>
                <text class="skip-text">Skip animation</text>
            </view>
            <view class="openBox">
                <u-button class="custom-style" @click="open" hover-class="none" :loading="loading">
                    Open Case {{ (box.coin_price * (selectedIndex + 1)).toFixed(2) }}
                    <i class="custom-icon custom-icon-objects-color_diamond"
                       style="padding-left: 10rpx;color: #ffffff"></i>
                </u-button>
            </view>
            <view class="openBoxPopup">
                <u-popup id="boxAnimation" ref="boxAnimation" mode="center" :mask-close-able="false"
                         :width="windowsWidth+'px'"
                >
                    <view v-for="index in selectedIndex+1" :key="index">
                        <openbox :goods-list="goodsList[index-1]" :prize-info="prizeInfo[index-1]"
                                 :delay="0.15 * (index-1)"
                                 :windowsWidth="windowsWidth"></openbox>
                        <view class="line" :style="{height : containerHeight * (selectedIndex+1)  + 'px'}"></view>
                    </view>
                </u-popup>
            </view>
            <view class="button-group">
                <view v-for="(button, index) in buttons" :key="index" class="button-item"
                      :class="{ 'active': selectedSaleAnalysis === button.label }" @click="handleButtonClick(button)">
                    {{ button.label }}
                </view>
            </view>
            <view v-if="selectedSaleAnalysis === 'Case Contents'" style="margin-top: 50rpx">
                <u-row :gutter="10">
                    <u-col span="6" v-for="(goods, index) in box.goodslist" :key="index">
                        <view class="goods" :style="getBackgroundStyle(goods.tag)">
                            <view class="goods-img">
                                <u-image width="300rpx" height="225rpx" :src="goods.image"></u-image>
                            </view>
                            <view class="goods-name">{{ goods.goods_name }}</view>
                            <view class="goods-rate">{{ goods.rate }}%</view>
                            <view class="goods-price">
                                {{ goods.price }}
                                <i class="custom-icon custom-icon-objects-color_diamond"
                                   style="padding-left: 10rpx;color: #65a5c7;font-size: 26rpx;"></i>
                            </view>
                        </view>
                    </u-col>
                </u-row>
            </view>
            <view v-if="selectedSaleAnalysis === 'Recently dropped'">
                <view class="openRecord">
                    <u-row :gutter="10" v-for="(item, index) in openRecord" :key="index" class="openRecord-row">
                        <u-col span="3" text-align="center">
                            <u-avatar :src="item.active" size="mini"></u-avatar>
                        </u-col>
                        <u-col span="5" text-align="center">
                            <view class="u-line-1">{{ item.create_time }}</view>
                        </u-col>
                        <u-col span="1">

                        </u-col>
                        <u-col span="3" style="margin: 0 auto" text-align="center">
                            <u-image :src="item.goods_image" width="120rpx" height="90rpx"></u-image>
                        </u-col>

                    </u-row>
                </view>
                <view v-if="noMore">
                    <u-divider style="padding: 30rpx" bg-color="#0f0e2d">There's no more data left</u-divider>
                </view>
            </view>
        </view>
        <!-- 开箱结束的弹窗 -->
        <view>
            <u-popup ref="acquire" mode="center" border-radius="25" :mask-close-able="false"
                     :width="windowsWidth+'px'">
                <view class="acquirePopup">
                    <!-- 1到3条数据 -->
                    <view v-if="prizeInfo.length <= 3" class="flex-container">
                        <view v-for="(item, index) in prizeInfo" :key="index" class="prize">
                            <view class="item"
                                  :style="getBackgroundStyle(item.tag)">
                                <u-image :src="item.image" width="100%" height="100%"></u-image>
                                <view class="item-text">{{ item.goods_name }}</view>
                            </view>

                        </view>
                    </view>

                    <!-- 4条数据 -->
                    <view v-if="prizeInfo.length === 4" class="flex-container">
                        <view v-for="(item, index) in prizeInfo.slice(0, 2)" :key="index" class="prize">
                            <view class="item"
                                  :style="getBackgroundStyle(item.tag)">
                                <u-image :src="item.image" width="100%" height="100%"></u-image>
                                <view class="item-text">{{ item.goods_name }}</view>
                            </view>
                        </view>
                    </view>
                    <view v-if="prizeInfo.length === 4" class="flex-container">
                        <view v-for="(item, index) in prizeInfo.slice(2, 4)" :key="index" class="prize">
                            <view class="item"
                                  :style="getBackgroundStyle(item.tag)">
                                <u-image :src="item.image" width="100%" height="100%"></u-image>
                                <view class="item-text">{{ item.goods_name }}</view>
                            </view>
                        </view>
                    </view>

                    <!-- 5条数据 -->
                    <view v-if="prizeInfo.length === 5" class="flex-container">
                        <view v-for="(item, index) in prizeInfo.slice(0, 3)" :key="index" class="prize">
                            <view class="item"
                                  :style="getBackgroundStyle(item.tag)">
                                <u-image :src="item.image" width="100%" height="100%"></u-image>
                                <view class="item-text">{{ item.goods_name }}</view>
                            </view>
                        </view>
                    </view>
                    <view v-if="prizeInfo.length === 5" class="flex-container">
                        <view v-for="(item, index) in prizeInfo.slice(3, 5)" :key="index" class="prize">
                            <view class="item"
                                  :style="getBackgroundStyle(item.tag)">
                                <u-image :src="item.image" width="100%" height="100%"></u-image>
                                <view class="item-text">{{ item.goods_name }}</view>
                            </view>
                        </view>
                    </view>

                    <view class="button">
                        <u-button type="primary" size="medium" @click="toPack">Put in your backpack</u-button>
                        <u-button type="success" size="medium" @click="toRecycle">
                            {{ totalValue.toFixed(2) }}
                            <i class="custom-icon custom-icon-objects-color_diamond"
                               style="padding-left: 10rpx;color: #65a5c7"></i>
                            displace
                        </u-button>
                    </view>

                </view>
            </u-popup>
        </view>
        <!-- 提示框 -->
        <u-toast ref="uToast"/>
        <!-- 回到顶部 -->
        <u-back-top :scroll-top="scrollTop"></u-back-top>
        <custom-tabbar></custom-tabbar>
    </view>
</template>

<script>
import Header from "@/components/header/header.vue";
import CustomTabbar from "@/components/tabbar/tabbar.vue";
import Openbox from "@/components/openBox/openBox.vue";

export default {
    name: 'boxDetail',
    components: {
        Header,
        Openbox,
        CustomTabbar
    },
    computed: {
        containerHeight() {
            return (this.windowsWidth / 5 + 20) / 4 * 3;
        },
    },
    mounted() {
        this.windowsWidth = this.$store.getters.getWindowsWidth;
        document.documentElement.style.setProperty('--windows-width', this.windowsWidth + 'px');
    },
    data() {
        return {
            windowsWidth: 0,
            box_id: '',
            box: {
                box_name: '',
                box_banner_images: [],
                coin_price: '',
                goodslist: [],
            },
            skip: false,
            buttonItems: [],
            // 当前选中的按钮索引
            selectedIndex: 0,

            selectedSaleAnalysis: 'Case Contents',
            buttons: [
                {
                    label: 'Case Contents'
                },
                {
                    label: 'Recently dropped'
                },
            ],
            // 最近掉落
            openRecord: [],
            total: '',
            current_page: 1,
            last_page: 0,
            // 滚动距离
            scrollTop: 0,
            // 到底
            noMore: false,
            // 定时器名称
            intervalId: null,
            // 开箱动画列表
            goodsList: [],
            // 获得开箱物品列表
            prizeInfo: [],
            // 总价值
            totalValue: 0,
            // 音频
            audio: null,
            // loading
            loading: false,
        };
    },
    // 接收参数
    onLoad(option) {
        this.box_id = option.box_id;
        if (option.free === 'true') {
            this.buttonItems = ['1'];
        } else {
            this.buttonItems = ['1', '2', '3', '4', '5'];
        }
        this.getBoxDetail();
        this.getRecentDrop();
        // this.intervalId = setInterval(this.getRecentDrop, 30000);
    },
    // onUnload() {
    //     // 页面卸载时清除定时器
    //     clearInterval(this.intervalId);
    //     this.intervalId = null
    // },

    // 滚动监听
    // onPageScroll(e) {
    //     this.scrollTop = e.scrollTop;
    // },
    // 触底加载更多
    // onReachBottom() {
    //     this.current_page++
    //     this.$u.api.getBoxOpenRecord({
    //         box_id: this.box_id,
    //         page: this.current_page
    //     }).then(res => {
    //         // 没数据
    //         if (res.data.data.length === 0) {
    //             this.noMore = true;
    //             this.boxList = []
    //             return
    //         }
    //         this.noMore = false;
    //         this.openRecord = this.openRecord.concat(res.data.data)
    //         this.total = res.data.total
    //         this.current_page = res.data.current_page
    //         this.last_page = res.data.last_page
    //     })
    // },
    methods: {
        // 返回
        back() {
            this.$u.route({
                type: 'navigateBack',
                delta: 1
            })
        },
        // 跳转帮助
        toHelp() {
            this.$refs.help.open()
        },
        // 计算背景图
        getBackgroundStyle(tag) {
            // 根据tag的值返回不同的背景图样式
            switch (tag) {
                case 'legend':
                    return 'background-image:linear-gradient(135deg,#252c55 15%,#685640 100%)'
                // return "background: linear-gradient(167deg,#4C5070 32.38%,#AC772B 100%),linear-gradient(90deg,#475176 0%,#ACE0F9 100%);";
                case 'chuanqi':
                    return 'background-image:linear-gradient(135deg,#252c55 15%,#692b45 100%)'
                    // return 'background: linear-gradient(167deg,#4C5070 27.46%,#902133 100%),linear-gradient(90deg,#FFF1EB 0%,#ACE0F9 100%)';
                case 'supreme':
                    return 'background-image:linear-gradient(135deg,#252c55 15%,#5e2b73 100%)'
                    // return 'background: linear-gradient(167deg,#4C5070 27.46%,#5E1D73 100%),linear-gradient(90deg,#FFF1EB 0%,#ACE0F9 100%);';
                case 'rare':
                    return 'background-image:linear-gradient(135deg,#252c55 15%,#3b317c 100%)'
                    // return 'background: linear-gradient(167deg,#4C5070 27.46%,#2C1D7E 100%),linear-gradient(90deg,#FFF1EB 0%,#ACE0F9 100%)';
                case 'normal':
                    return 'background-image:linear-gradient(135deg,#252c55 15%,#465075 100%)'
                    // return 'background: linear-gradient(167deg,#29315a 27.46%,#7E849C 100%),linear-gradient(90deg,#FFF1EB 0%,#ACE0F9 100%)';
                default:
                    return '';
            }
        },
        // 选择开几次
        selectItem(index) {
            this.selectedIndex = index;
        },
        // 开箱
        open() {
            // 清空
            this.totalValue = 0;
            this.prizeInfo = [];
            this.goodsList = [];
            this.loading = true;
            this.$nextTick(() => {
                // 创建盲盒支付订单
                this.$u.api.boxCreateOrder({
                    box_id: this.box_id,
                    num: this.selectedIndex + 1
                }).then(res => {
                    if (res.code === 1) {
                        // 创建订单成功 盲盒钻石支付
                        this.$u.api.boxCoinPay({
                            order_id: res.data.order_id
                        }).then(response => {
                            if (response.code === 1) {
                                // 获取用户信息
                                this.$u.api.getUserInfo().then(ress => {
                                    if (ress.code === 1) {
                                        const user = ress.data;
                                        // 提交mutation来更新Vuex中的状态
                                        this.$store.commit('user/SET_USER', user);
                                        // 保存到本地存储
                                        uni.setStorageSync('user', user);
                                    }
                                })
                                // 获得开箱物品
                                this.prizeInfo = response.data.prize.prizeInfo
                                // 开箱动画
                                if (!this.skip) {
                                    this.$nextTick(() => {
                                        for (const prizeInfoElement of this.prizeInfo) {
                                            this.goodsList.push(this.weightedRandomSelectionWithSpecificPosition(this.box.goodslist, prizeInfoElement));
                                            this.totalValue += parseFloat(prizeInfoElement.coin_price)
                                        }
                                    })
                                    this.audio = uni.createInnerAudioContext();
                                    this.audio.src = '/static/music/box.MP3';
                                    this.audio.play();
                                    this.$refs.boxAnimation.open();
                                    // 定时任务
                                    setTimeout(() => {
                                        this.openSuccess();
                                    }, 5000 + this.selectedIndex * 150);
                                } else {
                                    this.$nextTick(() => {
                                        for (const prizeInfoElement of this.prizeInfo) {
                                            this.totalValue += parseFloat(prizeInfoElement.coin_price)
                                        }
                                    })
                                    this.audio = uni.createInnerAudioContext();
                                    this.audio.src = '/static/music/skip.MP3';
                                    this.audio.play();
                                    setTimeout(() => {
                                        this.$refs.acquire.open()
                                    }, 500);
                                }
                                // 获取最近掉落
                                this.getRecentDrop()
                            } else {
                                this.$u.toast(response.msg)
                            }
                        })
                    } else {
                        this.$u.toast(res.msg)
                    }
                })
            })
            this.loading = false
        },

        // 获取盒子详情
        getBoxDetail() {
            this.$u.api.getBoxDetail({
                box_id: this.box_id
            }).then(res => {
                this.box = res.data;
            })
        },
        // 切换按钮
        handleButtonClick(button) {
            this.selectedSaleAnalysis = button.label; //切换选中的button
        },
        // 获取最近掉落
        getRecentDrop() {
            this.current_page = 1
            this.$u.api.getBoxOpenRecord({
                box_id: this.box_id,
                page: this.current_page
            }).then(res => {
                // 没数据
                if (res.data.data.length === 0) {
                    this.noMore = true;
                    this.boxList = []
                    return
                }
                this.noMore = false;
                this.openRecord = res.data.data
                this.total = res.data.total
                this.current_page = res.data.current_page
                this.last_page = res.data.last_page
            })
        },
        // 带特定位置的加权随机选择  在第八十个位置 插入特定元素
        weightedRandomSelectionWithSpecificPosition(goodsList, specificItem) {
            let selectedItems = [];
            let inserted = false; // 标记是否已插入特定元素

            while (selectedItems.length < 50) {
                let totalWeight = 0;
                for (let i = 0; i < goodsList.length; i++) {
                    totalWeight += parseFloat(goodsList[i].rate);
                }

                let random = Math.random() * totalWeight;
                let selectedItem;

                for (let i = 0; i < goodsList.length; i++) {
                    random -= parseFloat(goodsList[i].rate);
                    if (random < 0) {
                        selectedItem = goodsList[i];
                        break;
                    }
                }
                // 如果尚未插入特定元素，并且当前是第40个位置，插入特定元素
                if (!inserted && selectedItems.length === 45 - 1) {
                    selectedItems.push(specificItem);
                    inserted = true;
                } else {
                    selectedItems.push(selectedItem);
                }
            }
            return selectedItems;
        },
        // 展示开箱结果
        openSuccess() {
            this.$refs.boxAnimation.close();
            this.$refs.acquire.open();
        },
        // 放入背包
        toPack() {
            this.$refs.acquire.close();
        },
        // 回收
        toRecycle() {
            let prize_ids = this.prizeInfo.map(item => item.prize_id);
            prize_ids = prize_ids.join(',')
            this.$u.api.exchange({
                record_ids: prize_ids
            }).then(res => {
                if (res.code === 1) {
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'success'
                    });
                    this.$u.api.getUserInfo().then(res => {
                        if (res.code === 1) {
                            const user = res.data;
                            // 提交mutation来更新Vuex中的状态
                            this.$store.commit('user/SET_USER', user);
                            // 保存到本地存储
                            uni.setStorageSync('user', user);
                        }
                    })
                } else {
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'error'
                    });
                }
            })
            this.$refs.acquire.close();
        },
    }
}
</script>

<style lang="scss" scoped>
#boxAnimation {
    ::v-deep .u-drawer-center {
        align-items: flex-start;
    }
}

.back {
    line-height: 100rpx;
    //margin-left: 30rpx;
    color: white;
    font-size: 34rpx;
    background-image: url("@/static/images/header-bg.png");
    background-size: cover;
    height: 100rpx;
}

.popup {
    background-color: #0f0e2d;

    .title {
        text-align: center;
        padding: 20rpx;
    }

    .content {
        .item {
            padding: 20rpx;
        }
    }
}

@keyframes moveUpDown {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(20rpx);
    }
}

.title {
    height: 100rpx;
    background-image: url("@/static/images/boxDetail-title.png");
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.box {
    padding-top: 50rpx;
    padding-bottom: 50rpx;
    background-image: url("@/static/images/boxDetail-bg.jpg");
    background-size: 100% 100%;

    .box_banner {
        display: flex;
        flex-direction: column;

        .box_banner_images {
            display: flex;
            justify-content: center;
            animation: moveUpDown 2s infinite alternate;
        }
    }


}


.radio-group {
    display: flex;
    flex-direction: row;
    justify-content: center;
    padding: 30rpx;

    .radio-item {
        margin: 20rpx;

        .button {
            padding: 20rpx;
            border-radius: 10rpx;
            background-color: #3d477b;
            //border-width: 8px;
            //border-color: #e4c65c;

            color: #AAAAAA;
        }

        .radio-button {
            //border: 1px solid #e4c65c;
            background-color: #6888ce;
            color: #ffffff;
        }
    }


}

.skip {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;

    ::v-deep .u-switch {
        border: 3rpx solid #3f536e;
    }

    .skip-text {
        padding-left: 20rpx;
    }


}

.openBox {

    margin: 0 auto;
    padding: 20rpx;

    .custom-style {
        width: 50%;
        color: #ffffff;
        //background-color: #708fff;
        background-image: linear-gradient(135deg, #52E5E7 15%, #130CB7 100%)
    }
}

.button-group {
    display: flex;
    margin: 20rpx 30rpx;

    .button-item {
        flex: 1;
        text-align: center;
        padding: 10px;
        border: 1px solid #708fff;
        border-left: none;
        cursor: pointer;
    }
}

.button-group .button-item:first-child {
    border-radius: 20px 0 0 20px;
    //border-left: 1px solid #20264d;
}

.button-group .button-item:last-child {
    border-radius: 0 20px 20px 0;
}

.button-group .button-item:not(:first-child):not(:last-child) {
    border-radius: 0;
}

.active {
    background-image: linear-gradient(-225deg, #7DE2FC, #B9B6E5 100%);
    color: #000000;
    border: none;
    border-top: 1px solid #20264d;
    border-bottom: 1px solid #20264d;
}


.goods {
    margin: 10rpx;
    height: 370rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    background-size: 100% 100%;
    border-radius: 20rpx;

    position: relative;

    .goods-img {
        padding-top: 20rpx;
        margin: 0 auto;
    }

    .goods-name {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 80rpx;
        margin-top: 10rpx;
    }

    .goods-rate {
        position: absolute;
        top: 10rpx;
        right: 20rpx;
    }

    .goods-price {
        margin-top: 10rpx;
        margin-bottom: 20rpx;
    }
}

.openRecord {
    margin-top: 20rpx;
    padding: 20rpx;
    border-top: 1px solid #ccc;

    .openRecord-row {
        //border-bottom: 1px solid #ccc;
        padding: 20rpx;
        background: #20274c;
        border-radius: 20rpx;
        margin-bottom: 10rpx;

        .goods_name {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
}

.openBoxPopup {
    ::v-deep .u-mode-center-box {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        width: var(--windows-width);
    }
}


.line {
    margin: auto;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 2px;
    background-color: yellow;
    transform: translateX(-50%);
}


.flex-container {
    display: flex;
    justify-content: center;

    padding-bottom: 30rpx;

    .prize {
        display: flex;
        flex-direction: column;
        margin: 15rpx;

        .item {
            //display: flex;
            //justify-content: center;
            position: relative;
            background-position: center center;
            background-size: cover;
            object-fit: fill;
            width: 200rpx;
            height: 150rpx;
            padding: 20rpx;

            .item-text {
                position: absolute;
                bottom: 20rpx;
                //padding: 20rpx;
                //width: 200rpx;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
                width: 85%;
            }
        }


    }


}

.acquirePopup {
    padding: 30rpx;
    background-color: #0f0e2d;

    .button {
        display: flex;

        ::v-deep .u-size-medium {
            display: flex;
            width: 40%;
        }
    }
}

::v-deep .u-type-success {
    background-color: #0f0e2d;
    border: none;
}

::v-deep .u-type-error {
    background-color: #0f0e2d;
    border: none;
}
</style>
